using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Input;
using Prism.Commands;
using Prism.Mvvm;

namespace FileIO.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        private string _fileContent;
        private string _filePath;
        private string _statusMessage;

        public string FileContent
        {
            get => _fileContent;
            set => SetProperty(ref _fileContent, value);
        }

        public string FilePath
        {
            get => _filePath;
            set => SetProperty(ref _filePath, value);
        }

        public string StatusMessage
        {
            get => _statusMessage;
            set => SetProperty(ref _statusMessage, value);
        }

        public ICommand ReadFileCommand { get; }
        public ICommand WriteFileCommand { get; }
        public ICommand BrowseCommand { get; }
        public event Action? BrowseFileRequested;

        public MainWindowViewModel()
        {
            ReadFileCommand = new DelegateCommand(async () => await ReadFileAsync());
            WriteFileCommand = new DelegateCommand(async () => await WriteFileAsync());
            BrowseCommand = new DelegateCommand(OnBrowseFile);
        }

        private async Task ReadFileAsync()
        {
            try
            {
                if (string.IsNullOrEmpty(FilePath))
                {
                    StatusMessage = "请选择文件路径";
                    return;
                }

                if (!File.Exists(FilePath))
                {
                    StatusMessage = "文件不存在";
                    return;
                }

                FileContent = await File.ReadAllTextAsync(FilePath);
                StatusMessage = "文件读取成功";
            }
            catch (Exception ex)
            {
                StatusMessage = $"读取文件时发生错误: {ex.Message}";
            }
        }

        private async Task WriteFileAsync()
        {
            try
            {
                if (string.IsNullOrEmpty(FilePath))
                {
                    StatusMessage = "请选择文件路径";
                    return;
                }

                await File.WriteAllTextAsync(FilePath, FileContent);
                StatusMessage = "文件写入成功";
            }
            catch (Exception ex)
            {
                StatusMessage = $"写入文件时发生错误: {ex.Message}";
            }
        }

        private void OnBrowseFile()
        {
            BrowseFileRequested?.Invoke();
        }
    }
} 